package chenjiuxu.seniorui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import chenjiuxu.seniorui.R;

/**
 * Created by 15705 on 2017/12/26.
 * 图片放大镜效果
 */
public class MagnifierImgView extends View {
    private final Matrix matrix;
    private final Paint paint;
    private final Paint paintMagnifier;
    private final BitmapShader shader;
    private final Matrix matrixMagnifier;
    private Bitmap bitmap;
    private int imgWidth;
    private int imgHeight;
    private int radius = 200;
    private float touchY;
    private float touchX;
    private float scale;

    private boolean tag = true;

    public MagnifierImgView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img);
        imgWidth = bitmap.getWidth();
        imgHeight = bitmap.getHeight();
        matrix = new Matrix();
        paint = new Paint();
        matrixMagnifier = new Matrix();
        paintMagnifier = new Paint();
        shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        paintMagnifier.setShader(shader);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        drawImg(canvas);
        drawMagnifier(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                tag = true;
            case MotionEvent.ACTION_MOVE:
                touchX = event.getX();
                touchY = event.getY();
                matrixMagnifier.setScale(3 * scale, 3 * scale);
                matrixMagnifier.postTranslate(-2 * touchX, -2 * touchY);
                shader.setLocalMatrix(matrixMagnifier);
                break;
            case MotionEvent.ACTION_UP:
                tag = false;
                break;
        }
        invalidate();
        return true;
    }

    /**
     * 画放大镜
     */
    private void drawMagnifier(Canvas canvas) {
        if (tag) canvas.drawCircle(touchX, touchY - radius - 20, radius, paintMagnifier);
    }

    /**
     * 画图片
     */
    private void drawImg(Canvas canvas) {
        int width = getWidth();
        scale = (float) width / imgWidth;
        matrix.setScale(scale, scale);
        canvas.drawBitmap(bitmap, matrix, paint);
    }

}
